//
//  UITextField+inputAccessry.m
//

#import "UITextField+inputAccessry.h"
#import "UIColor+Expanded.h"
#import "UIView+Frame.h"
#import "UIView+Corner.h"
#import "UIButton+ExpandButton.h"

@implementation UITextField (inputAccessry)

- (void)setPlaceholder:(NSString *)placeholder {
    
    NSMutableDictionary * strAttributes = [NSMutableDictionary new];
    NSMutableParagraphStyle * paragraph = [[NSMutableParagraphStyle alloc]init];
    paragraph.lineSpacing = 2.0;
    [strAttributes setValue:paragraph forKey:NSParagraphStyleAttributeName];
    [strAttributes setValue:[UIColor colorWithRGBHexString:@"BBBBBB"] forKey:NSForegroundColorAttributeName];
    [strAttributes setValue:[UIFont systemFontOfSize:15] forKey:NSFontAttributeName];

    self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholder
                                                                 attributes:strAttributes];
}

static const char AttrPlaceholder = '\0';
- (void)setAttrPlaceholder:(NSString *)attrPlaceholder {
    objc_setAssociatedObject(self, &AttrPlaceholder, attrPlaceholder,
                             OBJC_ASSOCIATION_COPY_NONATOMIC);
    NSMutableDictionary * strAttributes = [NSMutableDictionary new];
    NSMutableParagraphStyle * paragraph = [[NSMutableParagraphStyle alloc]init];
    paragraph.lineSpacing = 2.0;
    [strAttributes setValue:paragraph forKey:NSParagraphStyleAttributeName];
    [strAttributes setValue:[UIColor colorWithRGBHexString:@"BBBBBB"] forKey:NSForegroundColorAttributeName];
    [strAttributes setValue:[UIFont systemFontOfSize:15] forKey:NSFontAttributeName];

    self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:attrPlaceholder
                                                                 attributes:strAttributes];
}

- (NSString *)attrPlaceholder {
    return objc_getAssociatedObject(self, &AttrPlaceholder);;
}


static const char PointView = '\0';
- (void)setPointView:(UIView *)pointView{
    
    // 存储新的
    objc_setAssociatedObject(self, &PointView, pointView, OBJC_ASSOCIATION_ASSIGN);
}

- (UIView *)pointView{
    
    return objc_getAssociatedObject(self, &PointView);
}

static const char ContentOffsetView = '\0';
- (void)setContentOffsetView:(UIView *)contentOffsetView{
    
    objc_setAssociatedObject(self, &ContentOffsetView,
    contentOffsetView, OBJC_ASSOCIATION_ASSIGN);
}

- (UIView *)contentOffsetView{
    
    return objc_getAssociatedObject(self, &ContentOffsetView);
}

static const char InitialPosition = '\0';
- (void)setInitialPosition:(NSNumber *)initialPosition{
    
    objc_setAssociatedObject(self, &InitialPosition, initialPosition, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSNumber *)initialPosition{
    
    return objc_getAssociatedObject(self, &InitialPosition);
}

static const char FieldDidChange = '\0';
- (void)setTextFieldDidChange:(TextFieldDidChange)textFieldDidChange{
    
    objc_setAssociatedObject(self, &FieldDidChange,
    textFieldDidChange, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (TextFieldDidChange)textFieldDidChange{
    
    return objc_getAssociatedObject(self, &FieldDidChange);
}

static const char TextViewDidEndEdit = '\0';
- (void)setTextViewDidEndEdit:(TextViewDidEndEditing)textViewDidEndEdit{
    
    objc_setAssociatedObject(self, &TextViewDidEndEdit,
                             textViewDidEndEdit, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (TextViewDidEndEditing)textViewDidEndEdit{
    
    return objc_getAssociatedObject(self, &TextViewDidEndEdit);
}


- (void)addObserverKeyboard:(UIView *)pointView contentOffsetView:(UIView *)contentOffsetView{
    self.pointView = pointView;
    self.contentOffsetView = contentOffsetView;
    // 添加通知监听见键盘弹出/退出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAction:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAction:) name:UIKeyboardDidChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAction:) name:UIKeyboardWillHideNotification object:nil];

}

// 键盘监听事件
- (void)keyboardAction:(NSNotification*)sender{
    
    if ([self isFirstResponder]) {
       
        UIView * responderView = self.pointView;
        // 通过通知对象获取键盘frame: [value CGRectValue]
        NSDictionary *useInfo = [sender userInfo];
        NSValue *value = [useInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        // <注意>具有约束的控件通过改变约束值进行frame的改变处理
        if([sender.name isEqualToString:UIKeyboardWillShowNotification]){
            
            CGRect frame2 = [responderView convertRect:responderView.bounds toView:nil];

            if ([value CGRectValue].origin.y<(frame2.origin.y+frame2.size.height)) {

                if ([self.contentOffsetView isKindOfClass:[UIScrollView class]]) {
                    UIScrollView * scrollView = (UIScrollView *) self.contentOffsetView;
                    [scrollView setContentOffset:CGPointMake(0, ((frame2.origin.y+frame2.size.height)-[value CGRectValue].origin.y)+scrollView.contentOffset.y)
                                             animated:YES];
                }else {
                    
                    self.initialPosition = @(self.contentOffsetView.y);
                    
                    CGRect rect = CGRectMake(self.contentOffsetView.x, self.contentOffsetView.y-((frame2.origin.y+frame2.size.height)-[value CGRectValue].origin.y), self.contentOffsetView.width, self.contentOffsetView.height);
                    
                    [self.contentOffsetView setFrame:rect];
                }
            }
            
        }else if([sender.name isEqualToString:UIKeyboardDidChangeFrameNotification]){
                          
        }else{
            
            if ([self.contentOffsetView isKindOfClass:[UIScrollView class]]) {
                UIScrollView * scrollView = (UIScrollView *) self.contentOffsetView;
                [scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
            }else {
                
                [self.contentOffsetView setFrame:CGRectMake(self.contentOffsetView.x, self.initialPosition.floatValue, self.contentOffsetView.width, self.contentOffsetView.height)];
            }
        }
    }
}

- (void)removeObserver{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}


- (void)setShowCustomInputAccessry:(BOOL)showCustomInputAccessry{
    
    if (showCustomInputAccessry&&self.enabled) {
        
        UIButton * hiddenbutton =[[UIButton alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,40 )];
        [hiddenbutton setTitle:@"Done" forState:UIControlStateNormal];
        [hiddenbutton setTitleColor:[UIColor colorWithRGBHexString:@"555555"] forState:UIControlStateNormal];
        hiddenbutton.titleLabel.font = [UIFont systemFontOfSize:15];
        hiddenbutton.titleLabel.textAlignment = NSTextAlignmentRight;
        hiddenbutton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [hiddenbutton addShadwCorners:UIRectEdgeTop fillColor:[UIColor blackColor] cornerRadii:CGSizeMake(hiddenbutton.width, hiddenbutton.height)];
        [hiddenbutton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 20)];
        
        __weak typeof(self) weakSelf = self;
        [hiddenbutton addClickBlock:^(UIButton * _Nonnull button) {
            [weakSelf resignFirstResponder];
        }];
        self.inputAccessoryView = hiddenbutton;
        self.inputAccessoryView.backgroundColor = [UIColor colorWithRGBHexString:@"eaeaea"];

    }else{
        self.inputAccessoryView =nil;
    }
    
}


#pragma 处理输入文字长度
static const char MaxLength = '\0';
- (void)setMaxLength:(NSNumber *)maxLength{

    objc_setAssociatedObject(self, &MaxLength,
    maxLength, OBJC_ASSOCIATION_ASSIGN);
    
    [self addObserverTextFieldDidChange];
}

- (NSNumber *)maxLength{

    return objc_getAssociatedObject(self, &MaxLength);
}


- (void)addObserverTextFieldDidChange{
    
    if (!self.maxLength) {
        self.maxLength = @(0xffffff);
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:UITextFieldTextDidChangeNotification object:self];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidEndEditing:) name:UITextFieldTextDidEndEditingNotification object:self];
}

- (void)textDidEndEditing:(NSNotification * )name {
    if(self.textViewDidEndEdit){
        self.textViewDidEndEdit(self);
    }
}



- (void)textFieldDidChange:(NSNotification * )name{

    UITextField * sender = name.object;
    
    if (sender != self) {
        return;
    }
    
    
    NSInteger kMaxLength = self.maxLength.integerValue;

    NSString *toBeString = self.text;

    NSString *lang = [[UIApplication sharedApplication]textInputMode].primaryLanguage; //ios7之前使用[UITextInputMode currentInputMode].primaryLanguage

    if ([lang isEqualToString:@"zh-Hans"]) { //中文输入

        UITextRange *selectedRange = [self markedTextRange];

        //获取高亮部分

        UITextPosition *position = [self positionFromPosition:selectedRange.start offset:0];

        if (!position) {// 没有高亮选择的字，则对已输入的文字进行字数统计和限制

            if (toBeString.length > kMaxLength) {

                self.text = [toBeString substringToIndex:kMaxLength];

            }

        }else{//有高亮选择的字符串，则暂不对文字进行统计和限制

        }

    }else{//中文输入法以外的直接对其统计限制即可，不考虑其他语种情况

        if (toBeString.length > kMaxLength) {

            self.text = [toBeString substringToIndex:kMaxLength];

        }

    }

    if (self.textFieldDidChange) {
        self.textFieldDidChange(self);
    }
    
}


@end
